package com.jhjx.wx.mp.controller;

import com.alibaba.fastjson.JSONObject;
import com.jhjx.wx.mp.utils.HttpClientUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.Map;


@Slf4j
@AllArgsConstructor
@RestController
@RequestMapping("/wx")
public class WxAuthController {

    /**
     * 微信授权
     * @param param
     * @return
     */
    @RequestMapping(value = "/auth",method = RequestMethod.POST)
    public Map<String, Object> greetUser(@RequestBody Map<String, Object> param) {
        // 获取授权信息
        JSONObject authInfo =  HttpClientUtils.httpGet("https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx3e9e6709927b3d9b&secret=9dc15d24a15c0f9f4ee720fbeb32b1ba&code="+param.get("code")+"&grant_type=authorization_code");
        // 获取用户唯一标识
        String openId = authInfo.get("openid").toString();
        // 获取网页 token
        String accessToken = authInfo.get("access_token").toString();
        // 获取用户信息
        JSONObject userWxInfo =  HttpClientUtils.httpGet("https://api.weixin.qq.com/sns/userinfo?access_token="+accessToken+"&openid="+openId+"&lang=zh_CN");
        param.put("code",200);
        param.put("openId",openId);
        if (userWxInfo != null) {
            userWxInfo.put("openId",userWxInfo.get("openid"));
            userWxInfo.put("headImgUrl",userWxInfo.get("headimgurl"));
            userWxInfo.put("groupId","0");
            userWxInfo.put("subscribe","1");
            userWxInfo.put("subscribeScene","ADD_SCENE_OTHERS");
            userWxInfo.put("qrScene","0");
            String sex = userWxInfo.get("sex").toString();
            if ("1".equals(sex)) {
                userWxInfo.put("sexDesc","男");
            } else if ("2".equals(sex)) {
                userWxInfo.put("sexDesc","女");
            } else {
                userWxInfo.put("sexDesc","未知");
            }
            // 查询当前用户有没有关注过该公众号
            JSONObject object =  HttpClientUtils.httpGet("http://127.0.0.1:8081/api/shop/getShopUserByOpenId?openId="+userWxInfo.get("openId").toString());
            if (null != object.get("data")) { // 若关注过则更新
                JSONObject json = new JSONObject();
                json.put("careFlag","1");
                json.put("openId",userWxInfo.get("openId"));
                JSONObject result =  HttpClientUtils.httpPost("http://127.0.0.1:8081/api/shop/updateCareFlagByOpenId",json);
                if ("-1".equals(result.get("code"))) {
                    param.put("code",-1);
                    log.error("更新关注发生异常！");
                }
            } else { // 若没有关注过则添加用户到本地数据库
                JSONObject result =  HttpClientUtils.httpPost("http://127.0.0.1:8081/api/shop/addCare",userWxInfo);
                if ("-1".equals(result.get("code"))) {
                    param.put("code",-1);
                    log.error("用户信息绑定发生异常！");
                }
            }
        }
        return param;
    }
}
